﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.Service.Data;
using System.Data.Common;

namespace Sinacor.OMM.Router.ResourceAccess
{
    public class OrderManager: BaseResourceAccess
    {
        public OrderManager(Int32 companyId)
            : base(companyId)
        {
            
        }

        /// <summary>
        /// Return list of opened orders
        /// </summary>
        /// <returns></returns>
        public List<ProcessEntity.Order> RetrieveOrders(DateTime operationDate)
        {
            string sql = string.Empty;
            List<ProcessEntity.Order> response = new List<Sinacor.OMM.Router.ProcessEntity.Order>();
            using (DbCommand command = this.DataBase.GetSqlStringCommand(" "))
            {
                command.CommandText =
                        @"SELECT  DISTINCT T.CD_CLIENTE, T.CD_NATOPE, T.CD_NEGOCIO, D.CD_OPERADOR
                        FROM    TORMOVD T, --ORDENS ABERTAS
                                TORDATMOV M  ,  --DATA DO SISTEMA 
                                TORDMEGA D ,
                                TBOCNFG_DIST_MSG_IAFR H
                        WHERE   (M.DT_DATMOV BETWEEN T.DT_DATORD AND T.DT_VALORD) AND
                                (D.NR_SEQORD = T.NR_SEQORD AND D.DT_DATORD = T.DT_DATORD AND D.NR_SUBSEQ = T.NR_SUBSEQ) AND 
                                T.IN_SITUAC <> 'D' --DIFERENTE DE CANCELADA 
                                AND T.TP_ORDEM IN (3,34,43) AND 
                                M.DT_DATMOV = :operationDate AND
                                (
                                (T.CD_CLIENTE = H.CD_CLIENTE AND D.CD_OPERADOR BETWEEN H.NUM_PRTA_INIC AND H.NUM_PRTA_FIM) OR
                                (D.CD_OPERADOR BETWEEN H.NUM_PRTA_INIC AND H.NUM_PRTA_FIM AND H.CD_CLIENTE IS NULL)
                                )";

                this.DataBase.AddInParameter(command, "operationDate", System.Data.DbType.Date, operationDate);
                response = this.FindAll<ProcessEntity.Order>(command, reader =>
                {
                    ProcessEntity.Order item = new Sinacor.OMM.Router.ProcessEntity.Order();

                    item.Client = reader.GetValue<Int32>("CD_CLIENTE");
                    item.Operator = reader.GetValue<Int32>("CD_OPERADOR");
                    item.Stock = reader.GetValue<String>("CD_NEGOCIO");
                    item.TradeSign = reader.GetValue<String>("CD_NATOPE");

                    return item;
                });
                return response;
            }
        }

    }
}
